import math
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch.nn import functional as F
from d2l import torch as d2l
from data_load_for_rnn import load_data_time_machine
from gru_data_load import dataset


###############################################################################################
class RNNModelScratch:
    """A RNN Model implemented from scratch."""

    def __init__(self, embedding_size, vocab_size, num_hiddens, device,
                 get_params, init_state, forward_fn):
        """Defined in :numref:`sec_rnn_scratch`"""
        self.vocab_size, self.num_hiddens = vocab_size, num_hiddens
        self.params = get_params(embedding_size, vocab_size, num_hiddens, device)
        self.init_state, self.forward_fn = init_state, forward_fn
        self.embedding_size = embedding_size
        self.embedding = nn.Embedding(vocab_size, embedding_size)

    def __call__(self, X, state):
        X = X.to(torch.long)
        X = self.embedding(X).permute([1, 0, 2])
        return self.forward_fn(X, state, self.params)

    def begin_state(self, batch_size, device):
        return self.init_state(batch_size, self.num_hiddens, device)


class RNNModel(nn.Module):
    """循环神经网络模型"""

    def __init__(self, rnn_layer, vocab_size, embedding_size, **kwargs):
        super(RNNModel, self).__init__(**kwargs)
        self.rnn = rnn_layer
        self.vocab_size = vocab_size
        self.num_hiddens = self.rnn.hidden_size
        self.embedding_size = embedding_size
        # 新增embeding
        self.embedding = nn.Embedding(vocab_size, embedding_size)
        # 如果RNN是双向的（之后将介绍），num_directions应该是2，否则应该是1
        if not self.rnn.bidirectional:
            self.num_directions = 1
            self.linear = nn.Linear(self.num_hiddens * self.num_directions, self.embedding_size)
        else:
            self.num_directions = 2
            self.linear = nn.Linear(self.num_hiddens * self.num_directions, self.embedding_size)
        self.linear_out = nn.Linear(self.embedding_size, vocab_size)

    def forward(self, inputs, state):
        # X = F.one_hot(inputs.T.long(), self.vocab_size)
        x = inputs.to(torch.long)
        x = self.embedding(x).permute([1, 0, 2])
        X = x.to(torch.float32)
        # 时间步数*批量大小,词表大小
        Y, state = self.rnn(X, state)
        # 全连接层首先将Y的形状改为(时间步数*批量大小,隐藏单元数)
        # 它的输出形状是(时间步数*批量大小,词表大小)。
        output = self.linear(Y.reshape((-1, Y.shape[-1])))
        output = self.linear_out(output)
        """
        X torch.Size([32, 28]) 初始信息
        X torch.Size([28, 32, 128])  经过词嵌入之后 T N D
        Y torch.Size([28, 32, 256])  T N H 经典多层LSTM结果
        output 经过进一步的处理后的结果 torch.Size([896, 932])   T N V
        state 2 torch.Size([2, 32, 256]) N H  一个是 H 一个是 C
        """
        print(len(state))
        return output, state

    def begin_state(self, device, batch_size=1):
        if not isinstance(self.rnn, nn.LSTM):
            # nn.GRU以张量作为隐状态
            return torch.zeros((self.num_directions * self.rnn.num_layers,
                                batch_size, self.num_hiddens),
                               device=device)
        else:
            # nn.LSTM以元组作为隐状态
            return (torch.zeros((
                self.num_directions * self.rnn.num_layers,
                batch_size, self.num_hiddens), device=device),
                    torch.zeros((
                        self.num_directions * self.rnn.num_layers,
                        batch_size, self.num_hiddens), device=device))


def try_gpu(i=0):
    """Return gpu(i) if exists, otherwise return cpu().

    Defined in :numref:`sec_use_gpu`"""
    if torch.cuda.device_count() >= i + 1:
        return torch.device(f'cuda:{i}')
    return torch.device('cpu')


def predict_ch8(prefix, num_preds, net, vocab, device):  # @save
    """在prefix后面生成新字符"""
    output_list = []
    state = net.begin_state(batch_size=1, device=device)
    outputs = [vocab[prefix]]
    get_input = lambda: torch.tensor([outputs[-1]], device=device).reshape((1, 1))
    # 预热期
    _, state = net(get_input(), state)
    for _ in range(num_preds):  # 预测num_preds步
        y, state = net(get_input(), state)
        arg_max_id = int(y.argmax(dim=1).reshape(1))
        if arg_max_id == vocab["<fin>"]:
            output_list.append(outputs)
            outputs = [vocab[prefix]]
        else:
            outputs.append(arg_max_id)
    new_out_list = []
    for outputs in output_list:
        if ' '.join([vocab.idx_to_token[i] for i in outputs]) not in new_out_list:
            new_out_list.append(' '.join([vocab.idx_to_token[i] for i in outputs]))

    return new_out_list


# 8.5.5. 梯度裁剪
def grad_clipping(net, theta):  # @save
    """裁剪梯度"""
    if isinstance(net, nn.Module):
        params = [p for p in net.parameters() if p.requires_grad]
    else:
        params = net.params
    norm = torch.sqrt(sum(torch.sum((p.grad ** 2)) for p in params))
    if norm > theta:
        for param in params:
            param.grad[:] *= theta / norm


# @save
def train_epoch_ch8(net, train_iter, loss, updater, device, use_random_iter):
    """训练网络一个迭代周期（定义见第8章）"""
    state, timer = None, d2l.Timer()
    metric = d2l.Accumulator(2)  # 训练损失之和,词元数量

    for X, Y in train_iter:
        # print("X",X.shape)
        if state is None or use_random_iter:
            # 在第一次迭代或使用随机抽样时初始化state
            state = net.begin_state(batch_size=X.shape[0], device=device)
        else:
            if isinstance(net, nn.Module) and not isinstance(state, tuple):
                # state对于nn.GRU是个张量
                state.detach_()
            else:
                # state对于nn.LSTM或对于我们从零开始实现的模型是个张量
                for s in state:
                    s.detach_()
        y = Y.T.reshape(-1)
        X, y = X.to(device), y.to(device)
        y_hat, state = net(X, state)

        """
        torch.Size([T, N, D]) torch.Size([T, N, H]) torch.Size([1, N, H])
        X torch.Size([32, 28])  (N,T)
        X_embbed (T, N, D)
        y_hat.shape torch.Size([896, 932])  (T, N, H)
        state.shape  torch.Size([32, 256])  (N, H)
        
        X torch.Size([32, 28]) 
        y_hat torch.Size([28, 32, 932])  (T, N, V)
        state[0] torch.Size([32, 256])      (N, H)
        """
        # print("x.shape,y_hat.shape, state.shape",X.shape,y_hat.shape, state[0].shape)
        l = loss(y_hat, y.long()).mean()
        if isinstance(updater, torch.optim.Optimizer):
            updater.zero_grad()
            l.backward()
            grad_clipping(net, 1)
            updater.step()
        else:
            l.backward()
            grad_clipping(net, 1)
            # 因为已经调用了mean函数
            updater(batch_size=1)

        metric.add(l * y.numel(), y.numel())
        # print(l, y.numel(), metric[0], metric[1],timer.stop())
    return math.exp(metric[0] / metric[1]), metric[1] / timer.stop()


def train_ch8(net, train_iter, vocab, lr, num_epochs, device,
              use_random_iter=False):
    """训练模型（定义见第8章）"""
    loss = nn.CrossEntropyLoss()
    animator = d2l.Animator(xlabel='epoch', ylabel='perplexity',
                            legend=['train'], xlim=[10, num_epochs])
    # 初始化
    if isinstance(net, nn.Module):
        updater = torch.optim.SGD(net.parameters(), lr)
    else:
        updater = lambda batch_size: d2l.sgd(net.params, lr, batch_size)
    predict = lambda prefix: predict_ch8(prefix, 100, net, vocab, device)
    # 训练和预测
    for epoch in range(num_epochs):
        ppl, speed = train_epoch_ch8(
            net, train_iter, loss, updater, device, use_random_iter)
        if (epoch + 1) % 50 == 0:
            print(predict('物理'))
            animator.add(epoch + 1, [ppl])
    print(f'困惑度 {ppl:.1f}, {speed:.1f} 词元/秒 {str(device)}')
    print(predict('每個'))
    print(predict('每'))


def predict(word, net, vocab, device):
    predict = lambda prefix: predict_ch8(prefix, 100, net, vocab, device)
    return [s.split(" ") for s in predict(word)]


"""
[{'alarm_level__level': 4, 'alarm_time': '2024-05-28 14:31:54', 'wechat_send_time': '2024-05-28 14:33:54', 'alarm_source__name': 'dks'}, 
{'alarm_level__level': 4, 'alarm_time': '2024-05-28 14:32:01', 'wechat_send_time': '2024-05-28 14:33:54', 'alarm_source__name': 'dks'}, 
{'alarm_level__level': 4, 'alarm_time': '2024-05-28 14:32:58', 'wechat_send_time': '2024-05-28 14:33:54', 'alarm_source__name': 'dks'}, 
{'alarm_level__level': 1, 'alarm_time': '2024-05-28 14:06:55', 'wechat_send_time': '2024-05-28 14:33:54', 'alarm_source__name': 'dks'}, 
{'alarm_level__level': 1, 'alarm_time': '2024-05-28 14:06:55', 'wechat_send_time': '2024-05-28 14:33:54', 'alarm_source__name': 'dks'}, 
{'alarm_level__level': 1, 'alarm_time': '2024-05-28 14:06:55', 'wechat_send_time': '2024-05-28 14:33:54', 'alarm_source__name': 'dks'}, 
{'alarm_level__level': 1, 'alarm_time': '2024-05-28 14:06:55', 'wechat_send_time': '2024-05-28 14:33:54', 'alarm_source__name': 'dks'}, 
{'alarm_level__level': 1, 'alarm_time': '2024-05-28 14:06:55', 'wechat_send_time': '2024-05-28 14:33:54', 'alarm_source__name': 'dks'}, 
{'alarm_level__level': 1, 'alarm_time': '2024-05-28 14:06:57', 'wechat_send_time': '2024-05-28 14:33:54', 'alarm_source__name': 'dks'}, 
{'alarm_level__level': 1, 'alarm_time': '2024-05-28 14:06:57', 'wechat_send_time': '2024-05-28 14:33:54', 'alarm_source__name': 'dks'}, 
{'alarm_level__level': 1, 'alarm_time': '2024-05-28 14:06:58', 'wechat_send_time': '2024-05-28 14:33:54', 'alarm_source__name': 'dks'}, 
{'alarm_level__level': 1, 'alarm_time': '2024-05-28 14:07:01', 'wechat_send_time': '2024-05-28 14:33:54', 'alarm_source__name': 'dks'}, 
{'alarm_level__level': 1, 'alarm_time': '2024-05-28 14:07:01', 'wechat_send_time': '2024-05-28 14:33:54', 'alarm_source__name': 'dks'}]
"""
